<template>
  <div class="page-container main-view">
    <el-row
      :gutter="0"
      v-show="dataContainer.showSearch"
      class="page-query-box"
    >
      <el-col :span="24" :xs="24">
        <el-form
          :model="dataContainer.form"
          ref="QueryFormRef"
          :inline="true"
          label-width="110px"
        >
          <el-row :gutter="0">
            <el-col :span="6" :xs="6">
              <el-form-item label="员工ID" prop="employeeId">
                <el-input
                  v-model="dataContainer.form.employeeId"
                  placeholder="请输入员工ID"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="真实姓名" prop="realName">
                <el-input
                  v-model="dataContainer.form.realName"
                  placeholder="请输入真实姓名"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="角色" prop="role">
                <el-select
                  v-model="dataContainer.form.role"
                  placeholder="请选择角色"
                  clearable
                  @clear="handleQuery"
                >
                  <el-option label="admin" value="admin" />
                  <el-option label="user" value="user" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label=" ">
                <el-button type="primary" @click="handleQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:search-bt.svg"
                  ></SvgIcon>
                  查询
                </el-button>
                <el-button @click="resetQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:redo.svg"
                  ></SvgIcon>
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <div class="table-box content-container page-content-box">
      <div class="top-container">
        <div class="left">
          <el-button
            v-if="hasPermi(['sys:user:add'])"
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            plain
            type="primary"
            v-if="hasPermi(['sys:user:export'])"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button
            plain
            type="danger"
            v-if="
              dataContainer.currDataList.length > 0 &&
              hasPermi(['sys:user:delete'])
            "
            @click="handleDelete(dataContainer.currDataList)"
          >
            批量删除
          </el-button>
        </div>
        <div class="right">
          <el-button circle @click="resetQuery">
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:redo.svg"
            ></SvgIcon>
          </el-button>
          <el-button
            circle
            @click="dataContainer.showSearch = !dataContainer.showSearch"
          >
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:search-bt.svg"
            ></SvgIcon>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="dataContainer.loading"
          :data="dataContainer.list"
          border
          @selection-change="handleSelectionChange"
          @cell-dblclick="handleCopyVale"
          @sort-change="handleSortChange"
          height="100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
            fixed="left"
          />
          <el-table-column
            label="ID"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="id"
          />
          <el-table-column
            label="员工ID"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="employeeId"
          />
          <el-table-column
            label="真实姓名"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="realName"
          />
          <el-table-column
            label="角色"
            show-overflow-tooltip
            align="center"
            prop="role"
            min-width="100"
          >
            <template #default="scope">
              <el-tag :type="getRoleType(scope.row.role)">{{
                scope.row.role
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="联系方式"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="contact"
          />
          <el-table-column
            label="创建时间"
            show-overflow-tooltip
            align="center"
            prop="createdAt"
            min-width="170"
          >
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="220"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button :text="true" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                :text="true"
                type="danger"
                v-if="hasPermi(['sys:user:delete'])"
                @click="handleDelete([scope.row.id])"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          v-show="true"
          :total="dataContainer.config.total"
          :background="true"
          :current-page="dataContainer.params.page"
          :page-size="dataContainer.params.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :pager-count="7"
          @size-change="
            (size) => {
              dataContainer.params.limit = size;
              getDataList();
            }
          "
          @current-change="
            (page) => {
              dataContainer.params.page = page;
              getDataList();
            }
          "
        />
      </div>
    </div>
    <EditDataDialog ref="EditDataDialogRef"></EditDataDialog>
  </div>
</template>

<script>
/**
 * 用户管理页面
 */
import {
  defineComponent,
  onBeforeUnmount,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onMounted,
  nextTick,
} from "vue";
import { useRouter } from "vue-router";
import { copyValue } from "@/common/OtherTools";
import DictTags from "@/components/DictTags.vue";
import { debounceFn } from "@/common/DebounceAndThrottle";
import {
  messageSuccess,
  messageError,
  confirm,
} from "@/action/MessagePrompt.js";
import EditDataDialog from "./components/EditDataDialog.vue";
import SvgIcon from "@/components/svgIcon/index.vue";
import { hasPermi } from "@/action/PowerTools";
import usersApi from "@/http/users.js";

export default defineComponent({
  components: {
    DictTags,
    EditDataDialog,
    SvgIcon,
  },
  setup() {
    onMounted(() => {
      getDataList();
    });

    const EditDataDialogRef = ref(null); //组件实例
    const router = useRouter();
    const dataContainer = reactive({
      loading: false,
      showSearch: true,
      form: {
        employeeId: "",
        realName: "",
        role: "",
      },
      params: {
        page: 1,
        limit: 10,
      },
      config: {
        total: 0,
      },
      list: [],
      allData: [],
      currDataList: [], // 初始化选择的数据列表
    });

    /** 获取角色标签类型 */
    function getRoleType(role) {
      switch (role) {
        case "admin":
          return "danger";
        case "user":
          return "success";
        default:
          return "info";
      }
    }

    /** 获取数据列表 */
    const getDataList = debounceFn(function () {
      dataContainer.loading = true;

      // 构建查询参数，过滤空值
      const queryParams = {};
      if (dataContainer.form.employeeId) queryParams.employeeId = dataContainer.form.employeeId;
      if (dataContainer.form.realName) queryParams.realName = dataContainer.form.realName;
      if (dataContainer.form.role) queryParams.role = dataContainer.form.role;

      usersApi
        .getUsers(queryParams)
        .then((res) => {
          // 处理API响应，支持直接数组或res.data格式
          const userList = Array.isArray(res) ? res : (res.data || res);
          dataContainer.allData = Array.isArray(userList) ? userList : [];
          dataContainer.config.total = dataContainer.allData.length;
          updatePageData();
        })
        .catch((err) => {
          console.error("获取用户列表失败", err);
          messageError(err.response?.data?.message || "获取用户列表失败");
          dataContainer.allData = [];
          dataContainer.list = [];
          dataContainer.config.total = 0;
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }, 300);

    function updatePageData() {
      const start =
        (dataContainer.params.page - 1) * dataContainer.params.limit;
      const end = start + dataContainer.params.limit;
      dataContainer.list = dataContainer.allData.slice(start, end);
    }

    /** 表格选择项变更 */
    function handleSelectionChange(selection) {
      dataContainer.currDataList = selection;
    }

    /** 双击单元格，复制单元格内容 */
    function handleCopyVale(_, __, ___, event) {
      copyValue(event.target.innerText);
      messageSuccess("复制成功，内容为：" + event.target.innerText);
    }

    /** 排序触发事件 */
    function handleSortChange(column) {
      dataContainer.form.orderByColumn = column.prop;
      dataContainer.form.isAsc = column.order;
      getDataList();
    }

    /** 搜索按钮操作 */
    function handleQuery() {
      dataContainer.params.page = 1;
      getDataList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
      dataContainer.form = {
        employeeId: "",
        realName: "",
        role: ""
      };
      handleQuery();
    }

    /** 导出数据 */
    function handleExport() {
      dataContainer.loading = true;
      
      // 构建导出参数
      const exportParams = {
        employeeId: dataContainer.form.employeeId || undefined,
        realName: dataContainer.form.realName || undefined,
        role: dataContainer.form.role || undefined
      };
      
      usersApi
        .getUsers(exportParams)
        .then((res) => {
          const userList = Array.isArray(res) ? res : (res.data || res);
          
          // 这里可以添加实际的导出逻辑，比如使用第三方库导出Excel
          console.log("导出用户数据", userList);
          messageSuccess(`准备导出 ${userList.length} 条用户数据`);
          
          // 实际项目中这里会调用导出API或使用前端导出库
          // 例如: exportToExcel(userList, '用户列表');
        })
        .catch((err) => {
          console.error("获取导出数据失败", err);
          messageError(err.response?.data?.message || "获取导出数据失败");
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }

    // 新增用户
    function handleAdd() {
      nextTick(() => {
        EditDataDialogRef.value
          .initData(true, {}, { isAdd: true, afterTitle: "-添加" })
          .then(() => {
            getDataList();
          })
          .catch(() => {});
      });
    }

    function handleEdit(row) {
      usersApi.getUserDetail(row.id)
        .then((res) => {
          const userData = res.data || res;
          nextTick(() => {
            EditDataDialogRef.value
              .initData(true, userData, { isAdd: false, afterTitle: "-编辑" })
              .then(() => {
                getDataList();
              })
              .catch(() => {});
          });
        })
        .catch((err) => {
          console.error("获取用户详情失败", err);
          messageError(err.response?.data?.message || "获取用户详情失败");
        });
    }

    function handleDelete(idsOrRows) {
      // 处理传入参数：可能是ID数组或行对象数组
      const ids = Array.isArray(idsOrRows) && idsOrRows.length > 0 
        ? (typeof idsOrRows[0] === 'object' ? idsOrRows.map(row => row.id) : idsOrRows)
        : [];
      
      if (ids.length === 0) {
        messageError("请选择要删除的用户");
        return;
      }

      const message = ids.length > 1 ? `确认删除选中的 ${ids.length} 个用户？` : "确认删除该用户？";
      confirm(message)
        .then(() => {
          dataContainer.loading = true;
          
          // 批量删除用户，使用 Promise.all 来处理
          const deletePromises = ids.map(id => 
            usersApi.deleteUser(id).catch(err => {
              console.error(`删除用户 ${id} 失败`, err);
              throw err;
            })
          );
          
          Promise.all(deletePromises)
            .then(() => {
              messageSuccess(`成功删除 ${ids.length} 个用户`);
              getDataList();
            })
            .catch((err) => {
              console.error("删除用户失败", err);
              messageError(err.response?.data?.message || "删除用户失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {});
    }

    /** 格式化日期 */
    function formatDate(dateTime) {
      if (!dateTime) return "-";
      return new Date(dateTime).toLocaleString();
    }

    return {
      dataContainer,
      getDataList,
      handleQuery,
      resetQuery,
      handleAdd,
      handleEdit,
      handleDelete,
      getRoleType,
      formatDate,
      hasPermi,
      EditDataDialogRef,
      // 其他必要返回
    };
  },
});
</script>

<style lang="scss" scoped>
.main-view {
  display: flex;
  flex-direction: column;
  > .page-query-box {
    margin: 0 0 10px 0 !important;
    padding: 10px 10px 0px 10px;
    :deep(.el-form-item) {
      margin-bottom: 10px !important;
    }
    :deep(.el-form-item--default) {
      width: 100%;
      margin-right: 0;
    }
  }
  > .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px 10px;
    box-sizing: border-box;
    background: #fff;
    > .top-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0px 0 10px 0;
    }
    > .table-container {
      flex: 1 1 auto;
      height: 0;
      overflow: auto;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    margin: 10px 0 0 0;
  }
}
</style>
